package com.zhengshang.web.controller.system;

import com.zhengshang.admin.security.service.TokenService;
import com.zhengshang.common.annotation.Log;
import com.zhengshang.common.constant.Constants;
import com.zhengshang.common.constant.UserConstants;
import com.zhengshang.common.core.controller.BaseController;
import com.zhengshang.common.core.domain.AjaxResult;
import com.zhengshang.common.core.domain.entity.SysMenu;
import com.zhengshang.common.core.domain.model.LoginUser;
import com.zhengshang.common.enums.BusinessType;
import com.zhengshang.common.utils.MessageUtils;
import com.zhengshang.common.utils.SecurityUtils;
import com.zhengshang.common.utils.ServletUtils;
import com.zhengshang.common.utils.StringUtils;
import com.zhengshang.system.service.ISysMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Locale;

/**
 * 菜单信息
 */
@RestController
@RequestMapping("/system/menu")
public class SysMenuController extends BaseController {
    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private TokenService tokenService;

    /**
     * 获取菜单列表
     */
    @PreAuthorize("@ss.hasPermi('system:menu:list')")
    @GetMapping("/list")
    public AjaxResult list(SysMenu menu) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Long userId = loginUser.getUser().getUserId();
        List<SysMenu> menus = menuService.selectMenuList(menu, userId);
        return AjaxResult.success(menus);
    }

    /**
     * 根据菜单编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:menu:query')")
    @GetMapping(value = "/{menuId}")
    public AjaxResult getInfo(@PathVariable Long menuId) {
        return AjaxResult.success(menuService.selectMenuById(menuId));
    }

    /**
     * 获取菜单下拉树列表
     */
    @GetMapping("/treeselect")
    public AjaxResult treeselect(SysMenu menu, HttpSession session) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Long userId = loginUser.getUser().getUserId();
        List<SysMenu> menus = menuService.selectMenuList(menu, userId);
        if( Locale.SIMPLIFIED_CHINESE.equals(session.getAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME))){
            return AjaxResult.success(menuService.buildMenuTreeZhSelect(menus));
        }else{
            return AjaxResult.success(menuService.buildMenuTreeEnSelect(menus));
        }

    }

    /**
     * 加载对应角色菜单列表树
     */
    @GetMapping(value = "/roleMenuTreeselect/{roleId}")
    public AjaxResult roleMenuTreeselect(@PathVariable("roleId") Long roleId , HttpSession session) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        List<SysMenu> menus = menuService.selectMenuList(loginUser.getUser().getUserId());
        AjaxResult ajax = AjaxResult.success();
        ajax.put("checkedKeys", menuService.selectMenuListByRoleId(roleId));
        if( Locale.US.equals(session.getAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME))){
            ajax.put("menus", menuService.buildMenuTreeEnSelect(menus));
        }else{
            ajax.put("menus", menuService.buildMenuTreeZhSelect(menus));
        }
        return ajax;
    }

    /**
     * 新增菜单
     */
    @PreAuthorize("@ss.hasPermi('system:menu:add')")
    @Log(title = "{menu.log.title}", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysMenu menu) {
        if (UserConstants.NOT_UNIQUE.equals(menuService.checkMenuZhNameUnique(menu))) {
            return AjaxResult.error(MessageUtils.message("menu.add.name.exists", menu.getMenuEnName()));
        } else if (UserConstants.NOT_UNIQUE.equals(menuService.checkMenuEnNameUnique(menu))) {
            return AjaxResult.error(MessageUtils.message("menu.add.name.exists", menu.getMenuEnName()));
        } else if (UserConstants.YES_FRAME.equals(menu.getIsFrame())
                && !StringUtils.startsWithAny(menu.getPath(), Constants.HTTP, Constants.HTTPS)) {
            return AjaxResult.error(MessageUtils.message("menu.add.frame.error", menu.getMenuEnName()));
        }
        menu.setCreateBy(SecurityUtils.getUsername());
        return toAjax(menuService.insertMenu(menu));
    }

    /**
     * 修改菜单
     */
    @PreAuthorize("@ss.hasPermi('system:menu:edit')")
    @Log(title = "{menu.log.title}", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysMenu menu) {
        if (UserConstants.NOT_UNIQUE.equals(menuService.checkMenuZhNameUnique(menu))) {
            return AjaxResult.error(MessageUtils.message("menu.edit.name.exists"), menu.getMenuEnName());
        } else if (UserConstants.NOT_UNIQUE.equals(menuService.checkMenuEnNameUnique(menu))
                &&!StringUtils.startsWithAny(menu.getPath(), Constants.HTTP, Constants.HTTPS)){
            return AjaxResult.error(MessageUtils.message("menu.add.frame.error", menu.getMenuEnName()));
        } else if (UserConstants.YES_FRAME.equals(menu.getIsFrame())
                && !StringUtils.startsWithAny(menu.getPath(), Constants.HTTP, Constants.HTTPS)) {
            return AjaxResult.error(MessageUtils.message("menu.edit.frame.error", menu.getMenuEnName()));
        } else if (menu.getMenuId().equals(menu.getParentId())) {
            return AjaxResult.error(MessageUtils.message("menu.edit.error", menu.getMenuEnName()));
        }
        menu.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(menuService.updateMenu(menu));
    }

    /**
     * 删除菜单
     */
    @PreAuthorize("@ss.hasPermi('system:menu:remove')")
    @Log(title = "{menu.log.title}", businessType = BusinessType.DELETE)
    @DeleteMapping("/{menuId}")
    public AjaxResult remove(@PathVariable("menuId") Long menuId) {
        if (menuService.hasChildByMenuId(menuId)) {
            return AjaxResult.error(MessageUtils.message("menu.del.child"));
        }
        if (menuService.checkMenuExistRole(menuId)) {
            return AjaxResult.error(MessageUtils.message("menu.del.assigned"));
        }
        return toAjax(menuService.deleteMenuById(menuId));
    }
}